<template>
  <div id="bar" style="max-height: 650px; width: 100%; height: 400px "></div>
</template>

<script>
  let echarts = require('echarts/dist/echarts')
  require('echarts/lib/chart/bar')
  require('echarts/lib/component/grid')
  require('echarts/lib/component/title')
  let ecStat = require('echarts-stat/src/ecStat')
  import {getHousePrice} from '../apis/api'
  export default {
    data () {
      return {
        title: this.$store.state.tabsList[this.$store.state.activeList.indexOf('4-1')].title
      }
    },
    methods: {
      drawpl () {
        getHousePrice(this.title).then(res => {
          let chart = echarts.init(document.getElementById('bar'))
          let girth = JSON.parse(res.data)
          let bins = ecStat.histogram(girth)
          let interval
          let min = Infinity
          let max = -Infinity
          let data = echarts.util.map(bins.data, function (item, index) {
            let x0 = bins.bins[index].x0
            let x1 = bins.bins[index].x1
            interval = x1 - x0
            min = Math.min(min, x0)
            max = Math.max(max, x1)
            return [x0, x1, item[1]]
          })
          function renderItem (params, api) {
            let yValue = api.value(2)
            let start = api.coord([api.value(0), yValue])
            let size = api.size([api.value(1) - api.value(0), yValue])
            let style = api.style()

            return {
              type: 'rect',
              shape: {
                x: start[0] + 1,
                y: start[1],
                width: size[0] - 1,
                height: size[1]
              },
              style: style
            }
          }
          let option = {
            title: {
              text: this.title,
              subtext: '单位：元 或 万元',
              left: 'center',
              top: 10
            },
            color: ['rgb(25, 183, 207)'],
            grid: {
              top: 80,
              containLabel: true
            },
            xAxis: [{
              type: 'value',
              min: min,
              max: max,
              interval: interval,
              name: '价格区间'
            }],
            yAxis: [{
              type: 'value',
              name: '个数'
            }],
            series: [{
              name: 'height',
              type: 'custom',
              renderItem: renderItem,
              label: {
                normal: {
                  show: true,
                  position: 'insideTop'
                }
              },
              encode: {
                x: [0, 1],
                y: 2,
                tooltip: 2,
                label: 2
              },
              data: data
            }]
          }
          chart.setOption(option)
        }, res => {
          this.$message({
            message: '数据不存在',
            type: 'error'
          })
        })
      }
    },
    mounted () {
      this.drawpl()
    }
  }
</script>
